import 'dart:convert';
import 'package:direct_link/direct_link.dart';
import 'package:flutter/services.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_workreportrecord/udt_tb_workreportrecord_product_select.dart';
import 'package:flutter_admin/utils/eventbus.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';

import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/udt_tb_workreportrecord_odoo_api.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/udt_tb_workreportrecord.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:quiver/strings.dart';
import '../../../generated/l10n.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qrscan/qrscan.dart' as scanner;

class UdtTbWorkreportrecordQrscan extends StatefulWidget {
  UdtTbWorkreportrecordQrscan();

  @override
  _UdtTbWorkreportrecordQrscanState createState() =>
      _UdtTbWorkreportrecordQrscanState();
}

class _UdtTbWorkreportrecordQrscanState
    extends State<UdtTbWorkreportrecordQrscan> {
  late UdtTbWorkreportrecord udtTbWorkreportrecord = UdtTbWorkreportrecord();

  EventChannel eventChannel = EventChannel("qrscan");

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  //班次
  late List<SelectOptionVO> shiftList = [];
  //报工人员
  late List<SelectOptionVO> reportworkerList = [];
  //工序
  late List<SelectOptionVO> pathList = [];

  var WRprocess = [];

  late var _subscription;

  String workshopCode = '';

  num quantity = 0;
  num coreNumber = 0;
  bool check = false;

  @override
  void initState() {
    _subscription = EventBus.getSubscriber()
        .where((event) => event["key"] == "workreportrecordQrscan")
        .listen(_onEnvent);
    super.initState();
    _loadSelectVO();
  }

  @override
  void dispose() {
    StoreUtil.write("key", "workreportrecord");
    _subscription.cancel();
    super.dispose();
  }

  Future _scan() async {
    await Permission.camera.request();
    String? barcode = await scanner.scan();
    if (barcode == null) {
      return;
    }
    _onEnvent({"scan":barcode});
  }

  //处理扫码后的结果
  void _onEnvent(dynamic obj) async {
    obj = obj["scan"];
    if (obj.contains("|")) {
      // 合单
      List objList = obj.split("|");
      var falg = await _getData(type: 3, barcode: objList[1]);
      if (falg != null) {
        return;
      }
      await _getData(type: 1,barcode: objList[0],);
      // await _getDataList();
    } else {
      // 人员码
      await _getData(type: 2, barcode: obj.toString());
    }
  }

  _loadSelectVO() async {
    shiftList = [];
    var res = await DynamicDataApi.getModels(model: 'base.shift');
    var starttime;
    var endtime;
    var index = 0;
    if (res.success!) {
      for (var i = 0; i < res.data.length; i++) {
        shiftList.add(SelectOptionVO(
            value: res.data[i]["id"].toString(),
            label: res.data[i]["shiftname"]));
        if (res.data[i]["shiftcode"] == "1001") {
          index = i;
          starttime = DateTime.parse(
              Utils.getDate() + " " + res.data[i]["starttime"] + ":00");
          endtime = DateTime.parse(
              Utils.getDate() + " " + res.data[i]["endtime"] + ":00");
        }
      }
    }
    if (!DateTime.now().isBefore(starttime) &&
        DateTime.now().isBefore(endtime)) {
      udtTbWorkreportrecord.shiftId = res.data[index]["id"].toString();
    } else {
      udtTbWorkreportrecord.shiftId =
          res.data[index == 0 ? 1 : 0]["id"].toString();
    }
    ResponseBodyApi res1 = await DynamicDataApi.getModels(
        model: "hr.department", key: 'id', val: num.parse(StoreUtil.read(Constant.KEY_PRODUCTIONSTATION)['workshopId']));
    if(res1.success!){
      workshopCode = res1.data[0]["department_code"];
    }
    // WRteam = await DynamicDataApi.getDictList('WRprocess');
    var WRprocessRes = await DynamicDataApi.dictionaryList('WRprocess');
    if(WRprocessRes.success!){
      WRprocess = WRprocessRes.data;
    }
    _loadData();
    setState(() {});
  }

  _loadData() {
    pathList = [];
    Map map = StoreUtil.read(Constant.KEY_PRODUCTIONSTATION);
    udtTbWorkreportrecord.stationId = map["stationId"].toString();
    udtTbWorkreportrecord.stationCode = map["stationCode"].toString();
    udtTbWorkreportrecord.stationName = map["stationName"].toString();
    udtTbWorkreportrecord.factoryId = map["factoryId"].toString();
    udtTbWorkreportrecord.factoryName = map["factoryName"].toString();
    udtTbWorkreportrecord.workshopId = map["workshopId"].toString();
    udtTbWorkreportrecord.workshopName = map["workshopName"].toString();
    udtTbWorkreportrecord.teamId = map["teamId"].toString();
    udtTbWorkreportrecord.teamCode = map["teamCode"].toString();
    udtTbWorkreportrecord.teamName = map["teamName"].toString();
    udtTbWorkreportrecord.qualifiedquantity = 0;
    udtTbWorkreportrecord.unqualifiedquantity = 0;
    udtTbWorkreportrecord.repairquantity = 0;
    // udtTbWorkreportrecord.cutting = 0;
    // udtTbWorkreportrecord.replacenumber = 0;
    reportworkerList = StoreUtil.read(Constant.KEY_REPORTWORKERLIST);
    if(reportworkerList.length == 1){
      udtTbWorkreportrecord.reportworkerId = reportworkerList[0].value.toString();
      udtTbWorkreportrecord.reportworkerName = reportworkerList[0].label.toString();
    }
    // udtTbWorkreportrecord.reportworkerId = reportworkerList[0].value.toString();
    StoreUtil.read(Constant.KEY_PATHLIST).forEach((element) {
      pathList.add(element);
    });
    if(pathList.length == 1){
      udtTbWorkreportrecord.processId = pathList[0].value.toString();
    }
    setState(() {});
  }

  _reset() {
    var reportworkerId = udtTbWorkreportrecord.reportworkerId;
    var reportworkerName = udtTbWorkreportrecord.reportworkerName;
    var processId = udtTbWorkreportrecord.processId;
    udtTbWorkreportrecord = UdtTbWorkreportrecord();
    udtTbWorkreportrecord.reportworkerId = reportworkerId;
    udtTbWorkreportrecord.reportworkerName = reportworkerName;
    udtTbWorkreportrecord.processId = processId;
    check = false;
    _loadSelectVO();
    // setState(() {});
  }

  int _getUserIndex(String id) {
    for (var i = 0; i < reportworkerList.length; i++) {
      if (id == reportworkerList[i].value) {
        return i;
      }
    }
    return -1;
  }

  _getData({int? type, String? barcode}) async {
    // todo type代表不同的对象（1：生产单号；2：人员；3：产品；）
    if (isBlank(barcode)) {
      return;
    }
    try {
      if (type == 1) {
        // todo 产品单号
        // formKey.currentState!.save();
        udtTbWorkreportrecord.productionorderno = barcode;
        // _getQualifiedquantity();
        setState(() {});
        return;
      }
      if (type == 2) {
        // todo 人员
        ResponseBodyApi res = await DynamicDataApi.getModels(
            model: "res.users", key: 'login', val: barcode);
        if (res.success!) {
          if (res.data.length == 0) {
            CryUtils.message("该人员不存在");
            return;
          } else if (res.data.length > 1) {
            CryUtils.message("编号重复");
            return;
          } else {
            var index = _getUserIndex(res.data[0]["id"].toString());
            if (index == -1) {
              CryUtils.message("该人员不属于${udtTbWorkreportrecord.teamName}");
              return;
            }
            formKey.currentState!.save();
            udtTbWorkreportrecord.reportworkerId =
            res.data[0]["id"] != false ? res.data[0]["id"].toString() : "";
            udtTbWorkreportrecord.reportworkerName =
                reportworkerList[index].label.toString();
            setState(() {});
          }
        }
        return;
      }
      if (type == 3) {
        ResponseBodyApi res = await DynamicDataApi.getModels(
            model: "product.template", key: 'default_code', val: barcode);
        if (res.success!) {
          if (res.data.length == 0) {
            CryUtils.message("该code已失效");
            _clearProductCode();
            return "";
          } else if (res.data.length > 1) {
            CryUtils.message("code重复");
            _clearProductCode();
            return "";
          } else {
            formKey.currentState!.save();
            udtTbWorkreportrecord.productId =
            res.data[0]["id"] != false ? res.data[0]["id"].toString() : "";
            udtTbWorkreportrecord.productCode =
            res.data[0]["default_code"] != false
                ? res.data[0]["default_code"].toString()
                : "";
            udtTbWorkreportrecord.productName = res.data[0]["name"] != false
                ? res.data[0]["name"].toString()
                : "";
            udtTbWorkreportrecord.spec = res.data[0]["description"] != false
                ? res.data[0]["description"].toString()
                : "";
            // _getQualifiedquantity();
            setState(() {});
          }
        }
      }
    } catch (e) {
      print(e);
      return "";
    }
  }

  bool _isProcess(processCode){
    for(var element in WRprocess){
      if(element['dictionaryname'] == processCode){
        return true;
      }
    }
    return false;
  }

  _getQualifiedquantity() async {
    if (!isBlank(udtTbWorkreportrecord.processId)
        &&!isBlank(udtTbWorkreportrecord.productId)
        &&!isBlank(udtTbWorkreportrecord.productionorderno)) {

      // 裁缆：OP0128
      // 包装：OP0052
      var qualifiedquantity = this.coreNumber;
      // LJQ-KJ 连接器-快接
      // 全部取个数
      if (udtTbWorkreportrecord.teamCode == 'LJQ-KJ'){
        qualifiedquantity = this.quantity;
      }else{
        ResponseBodyApi processRes = await DynamicDataApi.getModels(model: "mrp.routing.workcenter",key: 'id',val: udtTbWorkreportrecord.processId);
        if(processRes.success!&&processRes.data.length!=0&& _isProcess(processRes.data[0]['note'])){
          qualifiedquantity = this.quantity;
        }
      }
      ResponseBodyApi res = await UdtTbWorkreportrecordOdooApi.findAll(data: {"domainList":udtTbWorkreportrecord.toQualifiedquantityDomainList()});
      if (res.success!) {
        for (var i = 0; i < res.data.length; i++) {
          qualifiedquantity =
              qualifiedquantity -
                  res.data[i]["qualifiedquantity"];
          if(qualifiedquantity <= 0){
            break;
          }
        }
        udtTbWorkreportrecord.qualifiedquantity = qualifiedquantity>0?qualifiedquantity:0;
        setState(() {});
      }
    }
  }

  _clearProductCode() {
    setState(() {
      udtTbWorkreportrecord.productId = null;
      udtTbWorkreportrecord.productCode = null;
      udtTbWorkreportrecord.productName = null;
      udtTbWorkreportrecord.spec = null;
    });
  }

  _save(){
    FormState form = formKey.currentState!;
    form.save();
    udtTbWorkreportrecord.status = '0';
    udtTbWorkreportrecord.reportDate =
        DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now());
    UdtTbWorkreportrecordOdooApi.saveOrUpdate(
        udtTbWorkreportrecord.toOdooMap())
        .then((ResponseBodyApi res) {
      if (!res.success!) {
        // CryUtils.message(res.message!);
        return;
      }
      // Navigator.pop(context, true);
      CryUtils.message(S.of(context).saved);
      _reset();
    });
  }

  List<Widget> _formList(){
    List<Widget> list =[
      CrySelect(
        label: '生产工序',
        dataList: pathList,
        value: udtTbWorkreportrecord.processId,
        onSaved: (v) {
          udtTbWorkreportrecord.processId = v;
        },
        onChange: (v) async {
          if (udtTbWorkreportrecord.processId != v) {
            udtTbWorkreportrecord.processId = v;
            _getQualifiedquantity();
          }
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),
      Row(
        children: [
          Expanded(flex:3,child: CryInput(
            label: '产品名称',
            value: udtTbWorkreportrecord.productName,
            enable: false,
            onSaved: (v) {
              udtTbWorkreportrecord.productName = v;
            },
          ),),
          IconButton(onPressed: (){
            if(isBlank(udtTbWorkreportrecord.processId)){
              CryUtils.message("请选择工序");
              return ;
            }
            showDialog(
              barrierDismissible: false,
              context: context,
              builder: (BuildContext context) => Dialog(
                child: UdtTbWorkreportrecordProductSelect(
                    teamId: udtTbWorkreportrecord.teamId,
                    processId: udtTbWorkreportrecord.processId,
                    isMOP: workshopCode != 'LJQ'
                ),
              ),
            ).then((v) {
              if (v != null) {
                formKey.currentState?.save();
                udtTbWorkreportrecord.productId = v["product_id"]!=false?v["product_id"][0].toString():"";
                udtTbWorkreportrecord.productCode = v["default_code"]!=false?v["default_code"].toString():"";
                udtTbWorkreportrecord.productName = v["product_name"]!=false?v["product_name"].toString():"";
                udtTbWorkreportrecord.spec = v["pattern"]!=false?v["pattern"].toString():"";
                udtTbWorkreportrecord.productionorderno = v["order_number"]!=false?v["order_number"].toString():"";
                quantity = v["quantity"]!=false&&v["quantity"]!=null?int.parse(v["quantity"]):0;
                coreNumber = v["core_number"]!=false&&v["core_number"]!=null?int.parse(v["core_number"]):0;
                // udtTbWorkreportrecord.qualifiedquantity = v["core_number"]!=false&&v["core_number"]!=null?int.parse(v["core_number"]):0;
                setState(() {});
                _getQualifiedquantity();
              }
            });
          }, icon: Icon(Icons.search))
        ],
      ),
      CryInput(
        label: '规格型号',
        value: udtTbWorkreportrecord.spec,
        enable: false,
        onSaved: (v) {
          udtTbWorkreportrecord.spec = v;
        },
      ),
      Padding(
        padding: EdgeInsets.all(20),
        child: TextFormField(
          // focusNode: _focusNode,
          style: TextStyle(color: Colors.black),
          enabled: false,
          decoration: InputDecoration(
            labelText: '生产单号',
            contentPadding: EdgeInsets.symmetric(horizontal: 10),
          ),
          controller: TextEditingController(
              text: udtTbWorkreportrecord.productionorderno),
          onSaved: (v) {
            udtTbWorkreportrecord.productionorderno = v;
          },
          // validator: (v) {
          //   return v!.isEmpty ? S.of(context).required : null;
          // },
        ),
      ),
      CryInput(
        label: '生产车间',
        value: udtTbWorkreportrecord.workshopName,
        enable: false,
        onSaved: (v) {
          udtTbWorkreportrecord.workshopName = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),
      CryInput(
        label: '生产工位',
        value: udtTbWorkreportrecord.stationName,
        enable: false,
        onSaved: (v) {
          udtTbWorkreportrecord.stationName = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),
      CryInput(
        label: '班组',
        value: udtTbWorkreportrecord.teamName,
        enable: false,
        onSaved: (v) {
          udtTbWorkreportrecord.teamName = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),
      CryInput(
        label: '报工人',
        enable: false,
        value: udtTbWorkreportrecord.reportworkerName,
        onSaved: (v) {
          udtTbWorkreportrecord.reportworkerName = v;
        },
      ),

      CrySelect(
        label: '班次',
        value: udtTbWorkreportrecord.shiftId,
        dataList: shiftList,
        onSaved: (v) {
          udtTbWorkreportrecord.shiftId = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),

      // CryInputNum(
      //   label: '刀数',
      //   value: udtTbWorkreportrecord.cutting,
      //   onSaved: (v) {
      //     udtTbWorkreportrecord.cutting = v;
      //   },
      //   validator: (v) {
      //     return v!.isEmpty ? S.of(context).required : null;
      //   },
      // ),
      // CryInputNum(
      //   label: '换模个数',
      //   value: udtTbWorkreportrecord.replacenumber,
      //   onSaved: (v) {
      //     udtTbWorkreportrecord.replacenumber = v;
      //   },
      // ),
      new CheckboxListTile(
        // secondary: const Icon(Icons.production_quantity_limits),
        title: const Text('是否为返修产品'),
        value: this.check,
        onChanged: (bool? value) {
          setState(() {
            this.check = !this.check;
          });
        },
      ),

    ];
    if(check){
      list.add(
        CryInputNum(
          label: '返修数量',
          value: udtTbWorkreportrecord.repairquantity,
          onSaved: (v) {
            udtTbWorkreportrecord.repairquantity = v;
          },
          validator: (v) {
            return double.parse(v!) == 0 ? "返修数量不能为0" : null;
          },
        ),);
    }else{
      list.addAll([CryInputNum(
        label: '合格数量',
        value: udtTbWorkreportrecord.qualifiedquantity,
        onSaved: (v) {
          udtTbWorkreportrecord.qualifiedquantity = v;
        },
        validator: (v) {
          return double.parse(v!) == 0 ? "合格数量不能为0" : null;
        },
      ),
        CryInputNum(
          label: '不合格数量',
          value: udtTbWorkreportrecord.unqualifiedquantity,
          onSaved: (v) {
            udtTbWorkreportrecord.unqualifiedquantity = v;
          },
          validator: (v) {
            return v!.isEmpty ? S.of(context).required : null;
          },
        ),]);
    }
    list.add(CryInput(
      label: '备注',
      value: udtTbWorkreportrecord.remark,
      onSaved: (v) {
        udtTbWorkreportrecord.remark = v;
      },
    ),);
    return list;
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: _formList(),
      ),
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            if (isBlank(udtTbWorkreportrecord.productId)) {
              CryUtils.message("请选择产品");
              return;
            }
            if (isBlank(udtTbWorkreportrecord.reportworkerId)) {
              CryUtils.message("请扫描报工人");
              return;
            }
            if(check){
              udtTbWorkreportrecord.repairStatus = "1";
              cryConfirm(context, "是否为返修产品", (context) async {
                udtTbWorkreportrecord.qualifiedquantity = 0;
                udtTbWorkreportrecord.unqualifiedquantity = 0;
                _save();
              });
              return ;
            }
            udtTbWorkreportrecord.repairStatus = "0";
            udtTbWorkreportrecord.repairquantity = 0;
            udtTbWorkreportrecord.planQty = udtTbWorkreportrecord.qualifiedquantity;
            udtTbWorkreportrecord.routeRemark = "";
            _save();
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: "返回",
          onPressed: () {
            Navigator.pop(context, true);
          },
          iconData: Icons.arrow_back,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            return SizedBox.shrink();
          },
        ),
        title: Text("生产报工数据填报"),
        // actions: [
        //   CryButton(
        //     label: "扫码",
        //     onPressed: () {
        //       _scan();
        //     },
        //     iconData: Icons.qr_code_scanner_outlined,
        //   )
        // ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            form,
          ],
        ),
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
    // return result;
  }
}
